//
//  KLPlayingView.m
//  VibratingView
//
//  Created by apple on 2017/9/22.
//  Copyright © 2017年 NetEaseExam. All rights reserved.
//

#import "KLPlayingView.h"
#import "KLPlayingBar.h"

static const NSTimeInterval durationForAnimation = 0.25;

static const NSUInteger kBarsCount = 4;

@interface KLPlayingView (){
    NSArray *_bars;
    NSTimer *_timer;
    BOOL _animating;
}

@end

@implementation KLPlayingView

- (instancetype)initWithFrame:(CGRect)frame{
    self = [super initWithFrame:frame];
    if (self) {
        
        NSMutableArray *temp = [NSMutableArray array];
        
        for (int i = 0 ; i<kBarsCount; i++) {
            KLPlayingBar *bar0 = [KLPlayingBar layer];
            //        bar1.frequency = 0.15;
            bar0.amplitude = (arc4random_uniform(100) + 1) * 0.01;
            [self.layer addSublayer:bar0];
            [temp addObject:bar0];
        }
        
        _bars = [temp mutableCopy];
    }
    return self;
}

- (void)layoutSubviews{
    [super layoutSubviews];
    
    for (KLPlayingBar *bar in _bars) {
        NSUInteger index = [_bars indexOfObject:bar];
        CGFloat barHeight = self.bounds.size.height;
        CGFloat barWidth = self.bounds.size.width/_bars.count;
        CGFloat barX = index * barWidth;
        CGFloat barY = 0;
        bar.frame = CGRectMake(barX, barY, barWidth, barHeight);
    }
}

- (void)setColor:(UIColor *)color{
    _color = color;
    for (KLPlayingBar *bar in _bars) {
        bar.strokeColor = _color.CGColor;
    }
}

- (void)setBarWidth:(float)barWidth{
    _barWidth = barWidth;
    for (KLPlayingBar *bar in _bars) {
        bar.lineWidth = _barWidth;
    }
}

- (void)startAnimating{
    _animating = YES;
    _timer = [NSTimer scheduledTimerWithTimeInterval:durationForAnimation target:self selector:@selector(timerInvoke:) userInfo:nil repeats:YES];
}

- (void)stopAnimating{
    _animating = NO;
    [_timer invalidate];
}

- (BOOL)isAnimating{
    return _animating;
}

- (void)timerInvoke:(NSTimer *)timer{
    for (KLPlayingBar *bar in _bars) {
        bar.amplitude = (arc4random_uniform(100) + 1) * 0.01;
    }
}

/*
// Only override drawRect: if you perform custom drawing.
// An empty implementation adversely affects performance during animation.
- (void)drawRect:(CGRect)rect {
    // Drawing code
}
*/

@end
